package com.vehiclemanagement.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;  //BaseMapper：基础映射类，提供基本的CRUD操作
import com.baomidou.mybatisplus.core.metadata.IPage;      //IPage：分页数据接口（分页），获取一个数据当前页的对象
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;  //Page：分页插件，用于分页查询
import com.vehiclemanagement.entity.Binding;  //Binding：绑定关联实体类
import org.apache.ibatis.annotations.Delete;  //Delete：删除注解，用于删除数据
import org.apache.ibatis.annotations.Mapper;  //Mapper：映射注解，用于标识这是一个Mapper类
import org.apache.ibatis.annotations.Param;  //Param：参数注解，用于传递参数
import org.apache.ibatis.annotations.Select;  //Select：查询注解，用于查询数据

/**
 * 绑定关联Mapper接口
 */
@Mapper
 //继承BaseMapper类，实现Binding实体类
public interface BindingMapper extends BaseMapper<Binding> { 
        
    
    /**
     * 自定义分页查询，支持查询关联信息
     * 
     * @param page 分页对象
     * @param whereSql 自定义WHERE条件SQL（不包含WHERE关键字）
     * @return 分页结果
     */
    @Select("SELECT b.*, v.plate_number, d.name as driver_name, fc.card_number as fuel_card_number, ec.card_number as etc_card_number " +
            "FROM binding b " +
            "LEFT JOIN vehicle v ON b.vehicle_id = v.id " +
            "LEFT JOIN driver d ON b.driver_id = d.id " +
            "LEFT JOIN fuel_card fc ON b.fuel_card_id = fc.id " +
            "LEFT JOIN etc_card ec ON b.etc_card_id = ec.id " +
            "WHERE ${whereSql}")
        // Mapper注解的接口中，如果传入分页参数，则执行分页查询，否则执行普通查询，
        // 普通查询是根据@Select,@Update,@Delete,@Insert注解的SQL语句
        // MyBatis-Plus会根据传入的参数自动生成对应的SQL语句
    IPage<Binding> selectPageWithInfo(Page<Binding> page, @Param("whereSql") String whereSql);
    
    /**
     * 检查是否存在有效的绑定关系
     * 
     * @param vehicleId 车辆ID
     * @param driverId 驾驶员ID
     * @param fuelCardId 加油卡ID
     * @param etcCardId ETC卡ID
     * @return 是否存在
     */
    @Select("SELECT COUNT(*) FROM binding WHERE vehicle_id = #{vehicleId} AND driver_id = #{driverId} " +
            "AND fuel_card_id = #{fuelCardId} AND etc_card_id = #{etcCardId} AND status = 1 AND del_flag = 0")
    int existsActiveBinding(@Param("vehicleId") Long vehicleId, @Param("driverId") Long driverId,
                          @Param("fuelCardId") Long fuelCardId, @Param("etcCardId") Long etcCardId);
    
    /**
     * 物理删除绑定记录
     * 
     * @param id 绑定ID
     * @return 影响行数
     */
    @Delete("DELETE FROM binding WHERE id = #{id}")
    int deletePhysically(@Param("id") Long id);
} 